package framework.rpc.client;

import framework.rpc.protocol.http.transport.Invocation;
import framework.rpc.util.IoUtil;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClient {
    public String send(Invocation invocation, String hostName, Integer port) {
        try {
            URL url = new URL("http", hostName, port, "/");
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestMethod("POST");
            httpConnection.setDoOutput(true);

            OutputStream ops = httpConnection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(ops);
            oos.writeObject(invocation);
            oos.flush();
            oos.close();

            InputStream inputStream = httpConnection.getInputStream();
            return IoUtil.read(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
